package cn.ac.iie.system.service;

import cn.ac.iie.system.entity.users.UserDto;
import cn.ac.iie.system.repository.UsersRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.stereotype.Service;

@Service
public class UsersService {

  @Autowired
  private JdbcUserDetailsManager jdbcUserDetailsManager;

  @Autowired
  private PasswordEncoder passwordEncoder;

  @Autowired
  UsersRepository usersRepository;

  public boolean create(UserDto user) {
    // 构建用户详细信息
    UserDetails userDetails = User.builder()
        .username(user.getUsername())
        .password(user.getPassword())
        .roles(user.getRole())
        .passwordEncoder(password -> passwordEncoder.encode(password))
        .build();

    // 创建用户
    jdbcUserDetailsManager.createUser(userDetails);

    return false;
  }

  public void delete(String username) {
    jdbcUserDetailsManager.deleteUser(username);
  }
}
